//
//  RefreshCtrl.swift
//  我的微博
//
//  Created by shmily on 15/8/4.
//  Copyright © 2015年 Stanford-IOS8-Swift-shmilyAshen. All rights reserved.
//

import UIKit

/// 自定义下拉刷新
class RefreshCtrl: UIRefreshControl {
    
    //重写结束方法
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopLoad()
    }
    
    override init() {
        super.init()
        //设置视图
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    //MARK:- 设置界面
    private func setupUI() {
        //使菊花的背景透明
        tintColor = UIColor.clearColor()
        
        /// KVO self.bounds.height
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        addSubview(refreshView)
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
    }
    
    //键值监听到后触发事件
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //大于0不执行
        if frame.origin.y >= 0 {
            return
        }
        
        //刷新时更新菊花视图
        if refreshing {
            refreshView.beginLoad()
        }
        
        if frame.origin.y > -60  && !refreshView.isFreshed {
            refreshView.isFreshed = true
        } else if frame.origin.y < -60  && refreshView.isFreshed {
            refreshView.isFreshed = false
        }
    }
    
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    
    //MARK:- 懒加载
    private lazy var refreshView: RefreshView = RefreshView.freshView()
        
}

/// 下拉刷新的刷新视图
class RefreshView : UIView {
    
    /// 下拉刷新视图
    @IBOutlet weak var refreshArrowView: UIView!
    /// 刷新的菊花视图
    @IBOutlet weak var imgRound: UIImageView!
    /// 箭头的 imageView
    @IBOutlet weak var imgArrow: UIImageView!
   
    ///flag ,是否已经刷新过
    private var isFreshed = false {
        didSet{
            self.arrowAnimation()
        }
    }
    
    /// 从 xib 生成视图
    private class func  freshView() -> RefreshView {
        return  NSBundle.mainBundle().loadNibNamed("Refresh", owner: nil, options: nil).first as! RefreshView
    }
    
    /// 添加箭头转动动画
    private func arrowAnimation() {
        let rotation = isFreshed ? (M_PI - 0.001) : (M_PI + 0.001)
        UIView.animateWithDuration(0.25) { () -> Void in
            self.imgArrow.transform = CGAffineTransformRotate(self.imgArrow.transform, CGFloat(rotation))
        }
    }
    /// 正在加载数据的菊花
    func beginLoad() {
        //隐藏按钮
        refreshArrowView.hidden = true
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 8
        imgRound.layer.addAnimation(anim, forKey: "roundAnimation")
    }
    
    /// 关闭动画
    func stopLoad() {
        refreshArrowView.hidden = false
        imgRound.layer.removeAllAnimations()
    }
    
}
